package com.example.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.Post;
import com.example.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author JackLin
 * @since 2019-07-30
 */
@Slf4j
@Controller
public class UserController extends BaseController{

    /**
     * 用户主页，主要是显示用户信息和最近发表文章
     *
     * @param id  someUrl/{paramId}, 这时的paramId可通过 @PathVariable注解绑定它传过来的值到方法的参数上。
     * @return
     */
    @RequestMapping("/user/{id:\\d*}")
    public String home(@PathVariable Long id) {
        User user = userService.getById(id);
        user.setPassword(null);

        //查询30天以内的文章，1.先获取时间  2.再根据时间查询得到文章信息
        Date date30Before = DateUtil.offsetDay(new Date(), -30).toJdkDate();
        List<Post> posts = postService.list(new QueryWrapper<Post>()
                .eq("user_id", id)
                .ge("created", date30Before)
                .orderByDesc("created"));

        req.setAttribute("user", user);
        req.setAttribute("posts", posts);

        return "user/home";
    }

    @RequestMapping("/jump")
    public String jump(String username) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        Assert.notNull(user, "不存在此用户");

        return home(user.getId());
    }
}
